// Package analysis 实现谎言与真实性分析模块
// 基于四维量子系统的语义一致性检测
package analysis

import (
	"fmt"
	"math"
	"strings"
	"time"

	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/meso"
	"gitee.com/law2025/law-ai/quantum/internal/quantum-core/micro"
)

// Statement 陈述结构
type Statement struct {
	ID        string
	Content   string
	Timestamp time.Time
	Speaker   string
	Context   string
}

// TruthAnalysisResult 真实性分析结果
type TruthAnalysisResult struct {
	Statement           *Statement
	TruthScore          float64 // 真实性分数 (0-1)
	ConsistencyScore    float64 // 一致性分数 (0-1)
	CoherenceScore      float64 // 相干性分数 (0-1)
	EntropyLevel        float64 // 信息熵水平
	DeceptionIndicators []DeceptionIndicator
	Confidence          float64 // 置信度 (0-1)
	Analysis            string  // 分析说明
}

// DeceptionIndicator 欺骗指示器
type DeceptionIndicator struct {
	Type        string  // 指示器类型
	Severity    float64 // 严重程度 (0-1)
	Description string  // 描述
}

// TruthAnalyzer 真实性分析器
type TruthAnalyzer struct {
	encoder  *micro.QuantumSequenceEncoder
	balancer *meso.DynamicBalanceEngine
	history  []TruthAnalysisResult
}

// NewTruthAnalyzer 创建真实性分析器
func NewTruthAnalyzer() *TruthAnalyzer {
	return &TruthAnalyzer{
		encoder:  micro.NewQuantumSequenceEncoder(6, 0.85), // 使用6量子比特提高精度
		balancer: meso.NewDynamicBalanceEngine(0.75, 0.25),
		history:  make([]TruthAnalysisResult, 0),
	}
}

// AnalyzeStatement 分析单个陈述的真实性
func (ta *TruthAnalyzer) AnalyzeStatement(stmt *Statement) (*TruthAnalysisResult, error) {
	result := &TruthAnalysisResult{
		Statement:           stmt,
		DeceptionIndicators: make([]DeceptionIndicator, 0),
	}

	// 1. 量子编码分析 - 检测语义相干性
	coherence, err := ta.analyzeCoherence(stmt.Content)
	if err != nil {
		return nil, fmt.Errorf("相干性分析失败: %w", err)
	}
	result.CoherenceScore = coherence

	// 2. 熵分析 - 检测信息混乱度
	entropy := ta.analyzeEntropy(stmt.Content)
	result.EntropyLevel = entropy

	// 3. 一致性分析 - 与历史陈述对比
	consistency := ta.analyzeConsistency(stmt)
	result.ConsistencyScore = consistency

	// 4. 语言模式分析
	indicators := ta.analyzeLanguagePatterns(stmt.Content)
	result.DeceptionIndicators = append(result.DeceptionIndicators, indicators...)

	// 5. 计算综合真实性分数
	result.TruthScore = ta.calculateTruthScore(result)

	// 6. 计算置信度
	result.Confidence = ta.calculateConfidence(result)

	// 7. 生成分析报告
	result.Analysis = ta.generateAnalysis(result)

	// 保存到历史
	ta.history = append(ta.history, *result)

	return result, nil
}

// analyzeCoherence 分析语义相干性
func (ta *TruthAnalyzer) analyzeCoherence(text string) (float64, error) {
	// 将文本编码为量子态
	state, err := ta.encoder.EncodeMicroSequence([]byte(text))
	if err != nil {
		return 0, err
	}

	// 相干性高 = 语义一致性高 = 更可能真实
	return state.Coherence, nil
}

// analyzeEntropy 分析信息熵
func (ta *TruthAnalyzer) analyzeEntropy(text string) float64 {
	// 计算文本的信息熵
	// 高熵 = 信息混乱 = 可能存在欺骗
	
	// 统计字符频率
	freq := make(map[rune]int)
	total := 0
	for _, char := range text {
		freq[char]++
		total++
	}

	// 计算Shannon熵
	var entropy float64
	for _, count := range freq {
		if count > 0 {
			p := float64(count) / float64(total)
			entropy -= p * math.Log2(p)
		}
	}

	// 归一化到[0,1]
	maxEntropy := math.Log2(float64(len(freq)))
	if maxEntropy > 0 {
		entropy /= maxEntropy
	}

	return entropy
}

// analyzeConsistency 分析一致性
func (ta *TruthAnalyzer) analyzeConsistency(stmt *Statement) float64 {
	if len(ta.history) == 0 {
		return 0.5 // 没有历史数据，返回中性分数
	}

	// 与历史陈述对比
	var totalConsistency float64
	count := 0

	for _, past := range ta.history {
		if past.Statement.Speaker == stmt.Speaker {
			// 比较语义相似度
			similarity := ta.calculateSimilarity(stmt.Content, past.Statement.Content)
			totalConsistency += similarity
			count++
		}
	}

	if count == 0 {
		return 0.5
	}

	return totalConsistency / float64(count)
}

// analyzeLanguagePatterns 分析语言模式
func (ta *TruthAnalyzer) analyzeLanguagePatterns(text string) []DeceptionIndicator {
	indicators := make([]DeceptionIndicator, 0)

	// 1. 检测过度确定性词汇（谎言者常用）
	certaintyWords := []string{"绝对", "肯定", "一定", "必须", "从来", "总是", "never", "always", "absolutely"}
	certaintyCount := 0
	for _, word := range certaintyWords {
		certaintyCount += strings.Count(strings.ToLower(text), strings.ToLower(word))
	}
	
	textLen := float64(len([]rune(text)))
	if textLen > 0 && float64(certaintyCount)/textLen*100 > 2.0 {
		indicators = append(indicators, DeceptionIndicator{
			Type:        "过度确定性",
			Severity:    math.Min(float64(certaintyCount)/textLen*100/5.0, 1.0),
			Description: "使用过多绝对性词汇，可能试图强化信念",
		})
	}

	// 2. 检测否认词汇频率
	denialWords := []string{"没有", "不是", "从未", "绝不", "never", "not", "no"}
	denialCount := 0
	for _, word := range denialWords {
		denialCount += strings.Count(strings.ToLower(text), strings.ToLower(word))
	}
	
	if textLen > 0 && float64(denialCount)/textLen*100 > 3.0 {
		indicators = append(indicators, DeceptionIndicator{
			Type:        "过度否认",
			Severity:    math.Min(float64(denialCount)/textLen*100/6.0, 1.0),
			Description: "频繁使用否定词汇，可能在掩饰",
		})
	}

	// 3. 检测详细程度异常
	sentenceCount := float64(strings.Count(text, "。") + strings.Count(text, ".") + strings.Count(text, "！") + 1)
	avgSentenceLen := textLen / sentenceCount
	
	if avgSentenceLen > 50 {
		indicators = append(indicators, DeceptionIndicator{
			Type:        "过度详细",
			Severity:    math.Min((avgSentenceLen-50)/50, 1.0),
			Description: "陈述过于详细，可能在编造细节",
		})
	} else if avgSentenceLen < 10 && textLen > 20 {
		indicators = append(indicators, DeceptionIndicator{
			Type:        "过度简略",
			Severity:    (10 - avgSentenceLen) / 10,
			Description: "陈述过于简略，可能在隐藏信息",
		})
	}

	// 4. 检测第一人称代词使用（说真话者更多使用"我"）
	firstPersonWords := []string{"我", "我的", "I", "my", "mine"}
	firstPersonCount := 0
	for _, word := range firstPersonWords {
		firstPersonCount += strings.Count(text, word)
	}
	
	if textLen > 20 && float64(firstPersonCount)/textLen*100 < 0.5 {
		indicators = append(indicators, DeceptionIndicator{
			Type:        "回避主体",
			Severity:    0.5,
			Description: "较少使用第一人称，可能在推卸责任",
		})
	}

	return indicators
}

// calculateTruthScore 计算综合真实性分数
func (ta *TruthAnalyzer) calculateTruthScore(result *TruthAnalysisResult) float64 {
	// 权重分配
	weights := map[string]float64{
		"coherence":   0.35, // 相干性权重
		"consistency": 0.25, // 一致性权重
		"entropy":     0.20, // 熵权重（低熵=高真实性）
		"indicators":  0.20, // 欺骗指标权重
	}

	// 计算欺骗指标惩罚
	var indicatorPenalty float64
	for _, indicator := range result.DeceptionIndicators {
		indicatorPenalty += indicator.Severity
	}
	if len(result.DeceptionIndicators) > 0 {
		indicatorPenalty /= float64(len(result.DeceptionIndicators))
	}

	// 综合计算（熵是反向的，低熵=高真实）
	truthScore := weights["coherence"]*result.CoherenceScore +
		weights["consistency"]*result.ConsistencyScore +
		weights["entropy"]*(1.0-result.EntropyLevel) +
		weights["indicators"]*(1.0-indicatorPenalty)

	// 确保在[0,1]范围内
	return math.Max(0, math.Min(1, truthScore))
}

// calculateConfidence 计算置信度
func (ta *TruthAnalyzer) calculateConfidence(result *TruthAnalysisResult) float64 {
	// 基于数据质量和历史数据量计算置信度
	baseConfidence := 0.6

	// 有历史数据增加置信度
	if len(ta.history) > 0 {
		historyBonus := math.Min(float64(len(ta.history))/10.0*0.2, 0.2)
		baseConfidence += historyBonus
	}

	// 相干性高增加置信度
	if result.CoherenceScore > 0.8 {
		baseConfidence += 0.1
	}

	// 有明显欺骗指标增加置信度
	if len(result.DeceptionIndicators) > 2 {
		baseConfidence += 0.1
	}

	return math.Min(baseConfidence, 0.95)
}

// generateAnalysis 生成分析报告
func (ta *TruthAnalyzer) generateAnalysis(result *TruthAnalysisResult) string {
	var analysis strings.Builder

	// 整体评估
	if result.TruthScore > 0.7 {
		analysis.WriteString("✅ 该陈述显示出较高的真实性特征。")
	} else if result.TruthScore > 0.4 {
		analysis.WriteString("⚠️ 该陈述的真实性存在疑问，需要进一步核实。")
	} else {
		analysis.WriteString("❌ 该陈述显示出明显的欺骗性特征。")
	}

	analysis.WriteString(fmt.Sprintf("\n\n📊 真实性分数: %.1f%%", result.TruthScore*100))
	analysis.WriteString(fmt.Sprintf("\n🔗 语义相干性: %.1f%%", result.CoherenceScore*100))
	analysis.WriteString(fmt.Sprintf("\n📈 一致性: %.1f%%", result.ConsistencyScore*100))
	analysis.WriteString(fmt.Sprintf("\n🌀 信息熵: %.1f%%", result.EntropyLevel*100))

	// 欺骗指标
	if len(result.DeceptionIndicators) > 0 {
		analysis.WriteString("\n\n⚠️ 检测到以下疑点:")
		for i, indicator := range result.DeceptionIndicators {
			analysis.WriteString(fmt.Sprintf("\n  %d. %s (严重程度: %.1f%%) - %s",
				i+1, indicator.Type, indicator.Severity*100, indicator.Description))
		}
	} else {
		analysis.WriteString("\n\n✅ 未检测到明显的欺骗性语言模式。")
	}

	// 置信度说明
	analysis.WriteString(fmt.Sprintf("\n\n🎯 分析置信度: %.1f%%", result.Confidence*100))

	return analysis.String()
}

// calculateSimilarity 计算文本相似度（简化版）
func (ta *TruthAnalyzer) calculateSimilarity(text1, text2 string) float64 {
	// 使用简单的词汇重叠度计算相似度
	words1 := strings.Fields(text1)
	words2 := strings.Fields(text2)

	if len(words1) == 0 || len(words2) == 0 {
		return 0
	}

	// 构建词汇集合
	set1 := make(map[string]bool)
	for _, word := range words1 {
		set1[word] = true
	}

	// 计算重叠
	overlap := 0
	for _, word := range words2 {
		if set1[word] {
			overlap++
		}
	}

	// Jaccard相似度
	union := len(set1)
	for _, word := range words2 {
		if !set1[word] {
			union++
		}
	}

	if union == 0 {
		return 0
	}

	return float64(overlap) / float64(union)
}

// ComparStatements 比较多个陈述的一致性
func (ta *TruthAnalyzer) CompareStatements(statements []*Statement) map[string]interface{} {
	if len(statements) < 2 {
		return map[string]interface{}{
			"error": "需要至少2个陈述进行比较",
		}
	}

	results := make([]*TruthAnalysisResult, 0)
	for _, stmt := range statements {
		result, err := ta.AnalyzeStatement(stmt)
		if err == nil {
			results = append(results, result)
		}
	}

	// 计算整体一致性
	var avgConsistency float64
	var avgTruthScore float64
	for _, result := range results {
		avgConsistency += result.ConsistencyScore
		avgTruthScore += result.TruthScore
	}
	
	if len(results) > 0 {
		avgConsistency /= float64(len(results))
		avgTruthScore /= float64(len(results))
	}

	return map[string]interface{}{
		"statement_count":  len(statements),
		"analyzed_count":   len(results),
		"avg_consistency":  avgConsistency,
		"avg_truth_score":  avgTruthScore,
		"individual_results": results,
		"overall_assessment": ta.getOverallAssessment(avgTruthScore, avgConsistency),
	}
}

// getOverallAssessment 获取整体评估
func (ta *TruthAnalyzer) getOverallAssessment(truthScore, consistency float64) string {
	if truthScore > 0.7 && consistency > 0.7 {
		return "陈述群体显示出高度真实性和一致性"
	} else if truthScore < 0.4 || consistency < 0.4 {
		return "陈述群体存在明显矛盾或欺骗性特征"
	}
	return "陈述群体的真实性和一致性需要进一步验证"
}
